import { defineStore } from 'pinia'
import { setToken, removeToken, goTo } from '@/utils/common'
import { logout, getUserInfo } from '@/api/user'
interface Member {
	token : string | null
	info : {
		head_img : '',
		nickname : '',
		username : '',
		phone : '',
	}
}

const useMemberStore = defineStore('member', {
	state: () : Member => {
		return {
			token: uni.getStorageSync('token'),
			info: uni.getStorageSync('wap_user_info') || {
				head_img: '',
				nickname: '',
				username: '',
				phone: '',
			},
		}
	},
	actions: {
		async setToken(token : string) {
			this.token = token
			// console.log(token)
			setToken(token)
			await this.getUserInfo()
		},
		async getUserInfo() {
			if (!this.token) return
			await getUserInfo().then((res : any) => {
				// console.log(res.data)
				if(res.code == 200){
					this.info = res.data
					uni.setStorageSync('wap_user_info', this.info)
					uni.setStorageSync('wap_user_id', res.data.user_id)
				}else if(res.code == 600){
					this.logout();
				}
				
			}).catch(async () => {
				await this.logout();
			})
		},
		async logout(isRedirect : boolean = false) {
			if (!this.token) return
			this.token = ''
			this.info = null
			await logout().then(() => {
				removeToken()

				// 清除其他缓存
				isRedirect && goTo({ url: '/pages/index/index', mode: 'switchTab' })
			}).catch(() => {
				removeToken()

				// 清除其他缓存
				isRedirect && goTo({ url: '/pages/index/index', mode: 'switchTab' })
			})
		},
	}
})

export default useMemberStore